package com.sunrise.gateway.web.servlet;

import com.dap.utils.SpringUtils;
import com.sunrise.gateway.commons.CommonUtils;
import com.sunrise.gateway.web.core.ParamMapGetRequestEngine;
import com.sunrise.gateway.web.core.StringInputBodyPostRequestEngine;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CommonStringInputBodyCallbackServlet extends ServletBase {
    private ParamMapGetRequestEngine getEngine;
    private StringInputBodyPostRequestEngine postEngine;

    @Override
    public void init() throws ServletException {
        getEngine = SpringUtils.getBean(ParamMapGetRequestEngine.class);
        postEngine = SpringUtils.getBean(StringInputBodyPostRequestEngine.class);
        super.init();
    }

    @Override
    protected void doMyGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        execute(req, resp);
    }
    @Override
    protected void doMyPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        execute(req, resp);
    }


    private void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String invokeResult;
            if ("GET".equals(req.getMethod())) {
                invokeResult =
                        getEngine.execute(req, "CommonStringInputBodyCallback.", "CommonStringInputBodyCallback");
            } else {
                invokeResult =
                        postEngine.execute(req, "CommonStringInputBodyCallback.", "CommonStringInputBodyCallback");
            }
            CommonUtils.writeStrIntoResponse(invokeResult, resp);
        } catch (Exception e) {
            LOGGER.info("", e);
            CommonUtils.writeStrIntoResponse(e.getMessage(), resp);
        }
    }

}
